﻿
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using Twilio;


namespace EComAssignment.Models
{
    public static class AdminModel
    {
        public static string saveImage(HttpPostedFileBase file, HttpServerUtilityBase Server)
        {
            if (file == null) { return null; }
            if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") ||
                    (file.ContentType == "image/png"))//check allow jpg, gif, png
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss_") + fileName;
                var path = Path.Combine(Server.MapPath("~/Content/data/images/350.300/"), fileName);
                WebImage newImg = new WebImage(file.InputStream);
                int width = newImg.Width * 300 / newImg.Height;
                newImg.Resize(width, 300,true,false);
                if (newImg.Width > 300)
                {
                    newImg.Resize(300, 300, false, false);
                }
                newImg.Save(path);
                //file.SaveAs(path);//save image in folder                
                return fileName;
            }
            return null;
        }
        
        public static bool saveProduct(int id,string name,string description,int cateID,string type,
            int vol, int capacity, decimal price, int amount, string imgName,int? promotionID,string groupName, bool isSelling)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            
            var product = (from p in ctx.Products
                           where p.ID == id
                           select p).SingleOrDefault();
            if(product == null)
            {
                product = new Product();
            }
            product.name = name;
            product.description = description;
            product.category_ID = cateID;
            product.type = type;
            product.volume = vol;
            product.capacity = capacity;
            product.price = price;
            product.amount = amount;
            product.image_link = (imgName != null) ? imgName : product.image_link;
            product.promotion_ID = promotionID;
            product.sell_start_date = DateTime.Now;
            product.group_name = groupName;
            product.is_selling = isSelling;
            try
            {
                if (product.ID == 0)
                {
                    ctx.Products.InsertOnSubmit(product);                    
                }
                ctx.SubmitChanges();
            }
            catch (Exception e) 
            { 
                return false; 
            }
            
            return true;
        }

        public static bool deleteProduct(int id, HttpServerUtilityBase Server)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var pro = (from p in ctx.Products
                       where p.ID == id
                       select p).SingleOrDefault();            
            if (pro != null)
            {
                string completFileName = Server.MapPath("~/Content/data/images/350.300/" + pro.image_link);
                System.IO.File.Delete(completFileName);
                ctx.Products.DeleteOnSubmit(pro);
                ctx.SubmitChanges();
                return true;
            }
            return false;
        }

        public static string saveCateImage(HttpPostedFileBase file, HttpServerUtilityBase Server)
        {
            if (file == null) { return null; }
            if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") ||
                    (file.ContentType == "image/png"))//check allow jpg, gif, png
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss_") + fileName;
                var path = Path.Combine(Server.MapPath("~/Content/data/images/categories/"), fileName);
                WebImage newImg = new WebImage(file.InputStream);
                int width = newImg.Width * 300 / newImg.Height;
                newImg.Resize(width, 300, true, false);
                if (newImg.Width > 450)
                {
                    newImg.Resize(450, 300, false, false);
                }
                newImg.Save(path);
                //file.SaveAs(path);//save image in folder                
                return fileName;
            }
            return null;
        }

        public static bool saveCategory(int ID, string name, string address, string phoneNum, string imgName,
            string description, string email, string website)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cate = (from c in ctx.Categories
                        where c.ID == ID
                        select c).SingleOrDefault();
            if (cate == null)
            {
                cate = new Category();
            }
            cate.name = name;
            cate.address = address;
            cate.phone_number = phoneNum;
            cate.image_link = imgName != null ? imgName : cate.image_link;
            cate.description = description;
            cate.email = email;
            cate.website = website;
            try
            {
                if (cate.ID == 0)
                {
                    ctx.Categories.InsertOnSubmit(cate);
                }
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool deleteCategory(int id)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cate = (from c in ctx.Categories
                       where c.ID == id
                       select c).SingleOrDefault();
            if (cate != null)
            {
                ctx.Categories.DeleteOnSubmit(cate);
                ctx.SubmitChanges();
                return true;
            }
            return false;
        }

        public static bool saveAccount(int ID, string username, string password, string fullName, string email,
            string address, string phoneNum, int userLevel)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var acc = (from a in ctx.Accounts
                       where a.ID == ID
                       select a).SingleOrDefault();
            if (acc == null)
            {
                acc = new Account();
            }
            acc.username = username;
            acc.password = password;
            acc.full_name = fullName;
            acc.email = email;
            acc.address = address;
            acc.phone_number = phoneNum;
            acc.user_level = userLevel;
            try
            {
                if (acc.ID == 0)
                {
                    ctx.Accounts.InsertOnSubmit(acc);
                }
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool deleteAccount(int id)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var acc = (from a in ctx.Accounts
                        where a.ID == id
                        select a).SingleOrDefault();
            if (acc != null)
            {
                ctx.Accounts.DeleteOnSubmit(acc);
                ctx.SubmitChanges();
                return true;
            }
            return false;
        }

        public static bool changeOrderStatus(int orderID, string status)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var order = (from o in ctx.Orders
                         where o.ID == orderID
                         select o).SingleOrDefault();
            if (order == null) { return false; }
            order.status = status;
            ctx.SubmitChanges();
            return true;
        }

        public static bool deleteFeedback(int fbID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var feedback = (from fb in ctx.Feedbacks
                            where fb.ID == fbID
                            select fb).SingleOrDefault();
            if (feedback == null) { return false; }
            ctx.Feedbacks.DeleteOnSubmit(feedback);
            ctx.SubmitChanges();
            return true;
        }

        public static bool answerFeedback(int fbID, string body)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var feedback = (from fb in ctx.Feedbacks
                            where fb.ID == fbID
                            select fb).SingleOrDefault();
            if (feedback == null) { return false; }
            feedback.response = body;
            feedback.status = "Answered";
            ctx.SubmitChanges();

            var msg = "Cám ơn bạn đã đóng góp ý kiến cho chúng tôi để giúp website hoàn thiện hơn.\n\n"
                + "Ý kiến đóng góp của bạn:\n" + feedback.body + "\n\nChúng tôi xin trả lời như sau:\n" + body;
            AccountModel.sendEmail(feedback.email, feedback.title, msg);

            return true;
        }

        public static string saveSlider(HttpPostedFileBase file, HttpServerUtilityBase Server)
        {
            if (file == null) { return null; }
            if ((file.ContentType == "image/jpeg") || (file.ContentType == "image/gif") ||
                    (file.ContentType == "image/png"))//check allow jpg, gif, png
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss_") + fileName;
                var path = Path.Combine(Server.MapPath("~/Content/data/images/sliders/"), fileName);
                WebImage newImg = new WebImage(file.InputStream);
                int width = newImg.Width * 240 / newImg.Height;
                newImg.Resize(width, 240, true, false);
                if (newImg.Width > 590)
                {
                    newImg.Resize(590, 240, false, false);
                }
                newImg.Save(path);
                //file.SaveAs(path);//save image in folder                
                return fileName;
            }
            return null;
        }

        public static bool addSlider(string imgLink)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            Slider slider = new Slider()
            {
                image_link = imgLink
            };
            ctx.Sliders.InsertOnSubmit(slider);
            ctx.SubmitChanges();
            return true;
        }

        public static bool RemoveSlider(int ID, HttpServerUtilityBase Server)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var slider = (from s in ctx.Sliders
                          where s.ID == ID
                          select s).SingleOrDefault();
            if (slider == null) { return false; }
            string imgLink = slider.image_link;
            string completFileName = Server.MapPath("~/Content/data/images/sliders/" + imgLink);
            try
            {
                System.IO.File.Delete(completFileName);
                ctx.Sliders.DeleteOnSubmit(slider);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool saveAccount(string username, string password, string fullName, string email,
            string address, string phoneNum)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var acc = ctx.Accounts.Where(a => a.username==username).SingleOrDefault();
            if (acc == null) { return false; }            
            
            acc.password = password;
            acc.full_name = fullName;
            acc.email = email;
            acc.address = address;
            acc.phone_number = phoneNum;            
            try
            {                
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool deletePromotion(int promoID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var promo = ctx.Promotions.Where(p => p.ID == promoID).SingleOrDefault();
            if (promo == null) { return false; }
            try
            {
                ctx.Promotions.DeleteOnSubmit(promo);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool savePromotion(int? promoID,string title, string description, int rate,
            string start_date, string end_date)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var promo = ctx.Promotions.Where(p => p.ID == promoID).SingleOrDefault();
            if (promo == null) { promo = new Promotion(); }
            promo.title = title;
            promo.description = description;
            promo.rate = rate;
            try
            {
                promo.start_date = DateTime.ParseExact(start_date, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                promo.end_date = DateTime.ParseExact(end_date, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
                if (promo.ID == 0)
                {
                    ctx.Promotions.InsertOnSubmit(promo);
                }
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool saveMaps(string name, string address, string position)
        {
            string[] pos = position.Split(new char[] { '(', ')', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            Location loc = new Location()
            {
                name = name,
                address = address,
                lat = pos[0],
                lng = pos[1]
            };
            try
            {
                ctx.Locations.InsertOnSubmit(loc);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool deleteMaps(int mapID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var map = ctx.Locations.Where(l => l.ID == mapID).SingleOrDefault();
            if (map == null) { return false; }
            try
            {
                ctx.Locations.DeleteOnSubmit(map);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool updateMaps(int mapID, string address, string position)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var map = ctx.Locations.Where(l => l.ID == mapID).SingleOrDefault();
            if (map == null) { return false; }
            string[] pos = position.Split(new char[] { '(', ')', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            map.address = address;
            map.lat = pos[0];
            map.lng = pos[1];
            ctx.SubmitChanges();
            return true;
        }

        public static bool sendSMS(string toPhoneNum, string body)
        {
            try
            {
                string AccountSid = "AC415e43892056a6233f9836a0b87b32a3";
                string AuthToken = "da47eaeae60b3237b7f0e440f2e08595";
                var twilio = new TwilioRestClient(AccountSid, AuthToken);


                var sms = twilio.SendSmsMessage("+16122604428", toPhoneNum, body, "");
                
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public static bool sendSMSToOrderProcessing(int orderID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var order = ctx.Orders.Where(o => o.ID == orderID).SingleOrDefault();
            if (order == null) { return false; }
            var userPhoneNum = order.Account.phone_number;
            if (userPhoneNum.ElementAt(0) == '0') { userPhoneNum = userPhoneNum.Substring(1); }
            userPhoneNum = "+84" + userPhoneNum;
            string sms = "Don hang cua quy khach da duoc chap nhan. Chung toi se giao hang toi dia chi quy khach trong vong 24h!";
            bool success = sendSMS(userPhoneNum, sms);
            return success;
        }

        public static int saveNews(int ID, string title, string body)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var news = ctx.News.Where(n => n.ID == ID).SingleOrDefault();
            if (news == null) { news = new New(); }
            news.title = title;
            news.body = body;
            news.post_date = DateTime.Now;            
            try
            {
                if (news.ID == 0)
                {
                    ctx.News.InsertOnSubmit(news);
                }
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return 0;
            }
            return news.ID;
        }

        public static bool deleteNews(int ID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var news = ctx.News.Where(n => n.ID == ID).SingleOrDefault();
            if (news == null) { return false; }
            try
            {
                ctx.News.DeleteOnSubmit(news);
                ctx.SubmitChanges();
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
    }    
}